import { useState, useEffect, useRef } from 'react';
import QRCode from 'qrcode.react';
import { toast } from 'sonner';
import { useTheme } from '@/hooks/useTheme';
import { isValidUrl } from '@/lib/utils';
import { motion, AnimatePresence } from 'framer-motion';
import { QRCodeConfigPanel, QRCodeConfig } from '@/components/QRCodeConfigPanel';

export default function Home() {
  // 状态管理
  const [inputValue, setInputValue] = useState('');
  const [qrCodeValue, setQrCodeValue] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [generateType, setGenerateType] = useState<'text' | 'url'>('text');
  const [logoImage, setLogoImage] = useState<HTMLImageElement | null>(null);
  
  const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
  const { isDark } = useTheme();
  
  // 二维码样式配置
  const [qrCodeConfig, setQrCodeConfig] = useState<QRCodeConfig>({
    roundedCorners: 15, // 百分比，默认15%
    backgroundColor: '#FFFFFF',
    patternColor: '#000000',
    errorCorrectionLevel: 'H',
    logoUrl: '',
    logoSize: 20,
    logoRoundedCorners: 10, // 百分比
    size: 256, // 默认256px
    uploadedFile: undefined
  });

  // 自动生成二维码
  useEffect(() => {
    // 清除之前的定时器
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current);
    }


    if (inputValue.trim()) {
      // 立即显示加载状态
      setIsLoading(true);
      
      // 使用单个定时器，减少总延迟时间
      timeoutRef.current = window.setTimeout(() => {
        try {
          // 默认去除输入值的前后空格
          let valueToEncode = inputValue.replace(/^\s+|\s+$/g, '');
          // 根据选择的生成类型处理输入值
          if (generateType === 'url') {
            if (!valueToEncode.startsWith('http://') && !valueToEncode.startsWith('https://')) {
              valueToEncode = `https://${valueToEncode}`;
            }
          }          
          setQrCodeValue(valueToEncode);
          setIsLoading(false);
        } catch (error) {
          console.error('生成二维码失败:', error);
          setIsLoading(false);
          toast.error('生成二维码失败，请重试');
        }
      }, 300); // 减少延迟时间，提高响应速度
    } else {
      setQrCodeValue('');
      setIsLoading(false);
    }

    // 清理函数，确保组件卸载时清除定时器
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current);
        timeoutRef.current = null;
      }
    };
  }, [inputValue, generateType]);
  
  // 预加载logo图片
  useEffect(() => {
    if (qrCodeConfig.logoUrl) {
      const img = new Image();
      
      // 为非Data URL的图片设置crossOrigin属性以处理跨域问题
      if (!qrCodeConfig.logoUrl.startsWith('data:image/')) {
        img.crossOrigin = "anonymous";
      }
      
      img.onload = () => {
        setLogoImage(img);
        // 确保实时预览和下载使用相同的图片
        if (qrCodeConfig.logoUrl.startsWith('data:image/')) {
          console.log('本地图片加载成功');
        } else {
          console.log('远程图片加载成功，已设置跨域属性');
        }
      };
      
      img.onerror = () => {
        toast.error('Logo图片加载失败，可能是跨域问题或图片不可用，请尝试其他图片');
        setLogoImage(null);
        console.error('图片加载错误:', qrCodeConfig.logoUrl);
      };
      
      // 对于Data URL，我们可以直接使用
      img.src = qrCodeConfig.logoUrl;
      
      return () => {
        // 清理函数，防止内存泄漏
        setLogoImage(null);
      };
    } else {
      setLogoImage(null);
    }
  }, [qrCodeConfig.logoUrl]);

  // 根据背景色生成合适的边框颜色
  const getBorderColor = (backgroundColor: string): string => {
    // 解析颜色值
    const hex = backgroundColor.replace('#', '');
    const r = parseInt(hex.substring(0, 2), 16);
    const g = parseInt(hex.substring(2, 4), 16);
    const b = parseInt(hex.substring(4, 6), 16);
    
    // 计算亮度 (YIQ)
    const brightness = (r * 299 + g * 587 + b * 114) / 1000;
    
    // 根据亮度返回合适的边框颜色
    if (brightness > 200) {
      // 亮色背景，使用稍深的灰色
      return 'rgba(0, 0, 0, 0.1)';
    } else if (brightness > 128) {
      // 中等亮度背景，使用中等灰色
      return 'rgba(0, 0, 0, 0.2)';
    } else if (brightness > 64) {
      // 中等暗色背景，使用稍浅的灰色
      return 'rgba(255, 255, 255, 0.2)';
    } else {
      // 暗色背景，使用浅色边框
      return 'rgba(255, 255, 255, 0.3)';
    }
  };

  // 根据背景色生成边框样式
  const getBorderStyle = (backgroundColor: string): string => {
    const borderColor = getBorderColor(backgroundColor);
    return `0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06), 0 0 0 2px ${borderColor}`;
  };

  // 创建应用了所有样式的canvas
  const createStyledCanvas = (): HTMLCanvasElement | null => {
    try {
      // 先获取原始的二维码canvas
      const originalCanvas = document.querySelector('canvas') as HTMLCanvasElement;
      if (!originalCanvas) return null;
      
      // 创建一个新的canvas
      const styledCanvas = document.createElement('canvas');
      styledCanvas.style.position = 'absolute';
      styledCanvas.style.top = '-10000px';
      document.body.appendChild(styledCanvas);
      
      const ctx = styledCanvas.getContext('2d');
      if (!ctx) {
        document.body.removeChild(styledCanvas);
        return null;
      }
      
      // 设置新canvas的尺寸
      const borderSize = 20;
      const newSize = qrCodeConfig.size + (borderSize * 2);
      styledCanvas.width = newSize;
      styledCanvas.height = newSize;
      
      // 计算圆角的像素值（根据canvas尺寸的百分比）
      const roundedCornersPx = (newSize * qrCodeConfig.roundedCorners) / 100;
      
      // 绘制带圆角的背景
      ctx.fillStyle = qrCodeConfig.backgroundColor;
      ctx.beginPath();
      ctx.moveTo(roundedCornersPx, 0);
      ctx.lineTo(newSize - roundedCornersPx, 0);
      ctx.arcTo(newSize, 0, newSize, roundedCornersPx, roundedCornersPx);
      ctx.lineTo(newSize, newSize - roundedCornersPx);
      ctx.arcTo(newSize, newSize, newSize - roundedCornersPx, newSize, roundedCornersPx);
      ctx.lineTo(roundedCornersPx, newSize);
      ctx.arcTo(0, newSize, 0, newSize - roundedCornersPx, roundedCornersPx);
      ctx.lineTo(0, roundedCornersPx);
      ctx.arcTo(0, 0, roundedCornersPx, 0, roundedCornersPx);
      ctx.closePath();
      ctx.fill();
      
      // 添加边框，根据背景色动态调整
      ctx.strokeStyle = getBorderColor(qrCodeConfig.backgroundColor);
      ctx.lineWidth = 2;
      ctx.stroke();
      
      // 绘制原始二维码到新canvas上
      ctx.drawImage(originalCanvas, borderSize, borderSize);
      
      // 如果有logo URL，确保下载的图片中包含logo
      if (qrCodeConfig.logoUrl) {
        const logoSize = qrCodeConfig.size * (qrCodeConfig.logoSize / 100);
        const logoX = newSize / 2 - logoSize / 2;
        const logoY = newSize / 2 - logoSize / 2;
     
        // 在logo下方添加白色背景，确保在任何颜色的二维码上都清晰可见
        ctx.fillStyle = 'white';
        
        // 根据配置绘制带圆角的logo背景
        if (qrCodeConfig.logoRoundedCorners > 0) {
          // 计算圆角的像素值（根据logo尺寸的百分比）
          const roundedCornersPx = (logoSize * qrCodeConfig.logoRoundedCorners) / 100;
          
          // 创建带圆角的矩形
          ctx.beginPath();
          ctx.moveTo(logoX + roundedCornersPx, logoY);
          ctx.lineTo(logoX + logoSize - roundedCornersPx, logoY);
          ctx.arcTo(logoX + logoSize, logoY, logoX + logoSize, logoY + roundedCornersPx, roundedCornersPx);
          ctx.lineTo(logoX + logoSize, logoY + logoSize - roundedCornersPx);
          ctx.arcTo(logoX + logoSize, logoY + logoSize, logoX + logoSize - roundedCornersPx, logoY + logoSize, roundedCornersPx);
          ctx.lineTo(logoX + roundedCornersPx, logoY + logoSize);
          ctx.arcTo(logoX, logoY + logoSize, logoX, logoY + logoSize - roundedCornersPx, roundedCornersPx);
          ctx.lineTo(logoX, logoY + roundedCornersPx);
          ctx.arcTo(logoX, logoY, logoX + roundedCornersPx, logoY, roundedCornersPx);
          ctx.closePath();
          ctx.fill();
        } else {
          // 如果不需要圆角，使用圆形背景
          ctx.beginPath();
          ctx.arc(logoX + logoSize / 2, logoY + logoSize / 2, logoSize / 2, 0, Math.PI * 2);
          ctx.fill();
        }
     
        // 尝试绘制logo - 优先使用已加载的logoImage
        try {
          if (logoImage) {
            // 如果logoImage已加载，使用它
            if (qrCodeConfig.logoRoundedCorners > 0) {
              // 创建一个临时canvas用于裁剪
              const tempCanvas = document.createElement('canvas');
              tempCanvas.width = logoSize;
              tempCanvas.height = logoSize;
              const tempCtx = tempCanvas.getContext('2d');
              
              if (tempCtx) {
                // 计算圆角的像素值（根据logo尺寸的百分比）
                const roundedCornersPx = (logoSize * qrCodeConfig.logoRoundedCorners) / 100;
                
                // 在临时canvas上绘制带圆角的logo
                tempCtx.beginPath();
                tempCtx.moveTo(roundedCornersPx, 0);
                tempCtx.lineTo(logoSize - roundedCornersPx, 0);
                tempCtx.arcTo(logoSize, 0, logoSize, roundedCornersPx, roundedCornersPx);
                tempCtx.lineTo(logoSize, logoSize - roundedCornersPx);
                tempCtx.arcTo(logoSize, logoSize, logoSize - roundedCornersPx, logoSize, roundedCornersPx);
                tempCtx.lineTo(roundedCornersPx, logoSize);
                tempCtx.arcTo(0, logoSize, 0, logoSize - roundedCornersPx, roundedCornersPx);
                tempCtx.lineTo(0, roundedCornersPx);
                tempCtx.arcTo(0, 0, roundedCornersPx, 0, roundedCornersPx);
                tempCtx.closePath();
                tempCtx.clip();
                
                try {
                  // 绘制logo到临时canvas
                  tempCtx.drawImage(logoImage, 0, 0, logoSize, logoSize);
                  
                  // 将临时canvas的内容绘制到主canvas
                  ctx.drawImage(tempCanvas, logoX, logoY);
                } catch (drawError) {
                  console.error('Error drawing logo to temporary canvas:', drawError);
                  // 添加备用方案：绘制一个简单的占位符
                  ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
                  ctx.fillRect(logoX, logoY, logoSize, logoSize);
                }
              }
              
              // 清理临时canvas
              tempCanvas.remove();
            } else {
              try {
                // 如果不需要圆角，直接绘制logo
                ctx.drawImage(logoImage, logoX, logoY, logoSize, logoSize);
              } catch (drawError) {
                console.error('Error drawing logo directly:', drawError);
                // 添加备用方案：绘制一个简单的占位符
                ctx.fillStyle = 'rgba(255, 0, 0, 0.5)';
                ctx.fillRect(logoX, logoY, logoSize, logoSize);
              }
            }
          } else {
            // 如果logoImage未加载完成，添加等待提示
            console.log('Logo image not fully loaded yet');
            // 添加简单的加载指示器
            ctx.fillStyle = 'rgba(0, 0, 0, 0.2)';
            ctx.fillRect(logoX, logoY, logoSize, logoSize);
          }
        } catch (error) {
          console.error('Error drawing logo:', error);
          // 发生错误时，确保canvas仍然可以导出
        }
      }
      
      return styledCanvas;
    } catch (err) {
      console.error('创建样式化canvas失败:', err);
      return null;
    }
  };

  // 复制二维码到剪贴板
  const handleCopyToClipboard = async () => {
    if (!qrCodeValue) return;

    try {
      // 创建一个临时canvas来应用样式并复制
      const canvas = createStyledCanvas();
      if (canvas) {
        const dataUrl = canvas.toDataURL('image/png');
        const blob = await (await fetch(dataUrl)).blob();
        await navigator.clipboard.write([
          new ClipboardItem({
            'image/png': blob
          })
        ]);
        toast.success('二维码已复制到剪贴板');
        // 清理临时canvas
        document.body.removeChild(canvas);
      }
    } catch (err) {
      console.error('复制失败:', err);
      toast.error('复制失败，请右键保存图片');
    }
  };
  
  // 保存二维码图片
  const handleDownloadQRCode = () => {
    if (!qrCodeValue) return;
    
    try {
      const styledCanvas = createStyledCanvas();
      if (styledCanvas) {
        // 从样式化canvas生成下载数据
        try {
          const dataUrl = styledCanvas.toDataURL('image/png');
          const link = document.createElement('a');
          link.href = dataUrl;
          link.download = 'qrcode.png';
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          document.body.removeChild(styledCanvas);
          toast.success('二维码已下载');
        } catch (dataUrlError) {
          console.error('生成图片数据失败:', dataUrlError);
          // 检查是否是跨域问题导致的
          if (dataUrlError instanceof DOMException && 
              (dataUrlError.name === 'SecurityError' || dataUrlError.message.includes('tainted'))) {
            toast.error('由于跨域安全限制，无法下载带此logo的二维码。请尝试使用本地上传的图片或其他logo。');
          } else {
            toast.error('下载失败，请右键保存图片');
          }
          // 清理canvas
          document.body.removeChild(styledCanvas);
        }
      }
    } catch (err) {
      console.error('下载失败:', err);
      toast.error('下载失败，请重试或右键保存图片');
    }
  };

  return (
    <>
      <div className={`w-full p-6 sm:p-8 rounded-2xl shadow-lg ${isDark ? 'bg-gray-800' : 'bg-white'} transition-colors duration-300 mb-6`}>
        <h2 className="text-xl sm:text-2xl font-medium mb-6 text-center">
          即时生成您的专属二维码
        </h2>
        
        {/* 输入区域 */}
        <div className="mb-8">
          {/* 生成类型选择 */}
          <div className="flex flex-wrap gap-3 mb-4">
            <button
              onClick={() => setGenerateType('text')}
              className={`px-4 py-2 rounded-lg transition-colors ${
                generateType === 'text' 
                  ? 'bg-blue-500 text-white' 
                  : isDark 
                    ? 'bg-gray-700 text-gray-300 hover:bg-gray-600' 
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              <i className="fa-file-lines mr-1"></i> 文本
            </button>
            
            <button
              onClick={() => setGenerateType('url')}
              className={`px-4 py-2 rounded-lg transition-colors ${
                generateType === 'url' 
                  ? 'bg-green-500 text-white' 
                  : isDark 
                    ? 'bg-gray-700 text-gray-300 hover:bg-gray-600' 
                    : 'bg-gray-100 text-gray-600 hover:bg-gray-200'
              }`}
            >
              <i className="fa-globe mr-1"></i> 网址
            </button>
          </div>
          
          <label htmlFor="qr-input" className={`block text-sm font-medium mb-2 ${isDark ? 'text-gray-300' : 'text-gray-600'}`}>
            {generateType === 'text' ? '输入文本内容' : '输入网址链接'}
          </label>
          
          <textarea
            id="qr-input"
            value={inputValue}
            onChange={(e) => setInputValue(e.target.value)}
            placeholder={generateType === 'text' ? '输入文本内容，二维码将自动生成...' : '输入网址链接，二维码将自动生成...'}
            className={`w-full p-4 h-32 sm:h-40 rounded-xl border focus:ring-2 focus:ring-blue-500 focus:border-transparent resize-none transition-all ${
              isDark 
                ? 'bg-gray-700 border-gray-600 text-white placeholder-gray-400' 
                : 'bg-gray-50 border-gray-200 text-gray-800 placeholder-gray-400'
            }`}
          />
        </div>
        
        {/* 二维码显示区域 */}
        <div className="flex flex-col items-center">
          <AnimatePresence mode="wait">
            {qrCodeValue && !isLoading ? (
              <motion.div
                key="qrcode"
                initial={{ opacity: 0, scale: 0.9 }}
                animate={{ opacity: 1, scale: 1 }}
                exit={{ opacity: 0, scale: 0.9 }}
                transition={{ duration: 0.3 }}
                className="relative mb-6"
              >
                <div 
                  className="relative p-4 shadow-md"
                  style={{ 
                    backgroundColor: qrCodeConfig.backgroundColor,
                    boxShadow: getBorderStyle(qrCodeConfig.backgroundColor),
                    borderRadius: `${qrCodeConfig.roundedCorners}%`
                  }}
                >
                  <QRCode 
                    value={qrCodeValue} 
                    size={qrCodeConfig.size} 
                    level={qrCodeConfig.errorCorrectionLevel} 
                    includeMargin={false}
                    fgColor={qrCodeConfig.patternColor}
                    bgColor={qrCodeConfig.backgroundColor}
                  />
                  
                  {/* 实时预览logo */}
                  {qrCodeConfig.logoUrl && (
                    <div className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 flex items-center justify-center">
                      <div 
                        className="bg-white flex items-center justify-center overflow-hidden"
                        style={{ 
                          width: `${qrCodeConfig.logoSize * (qrCodeConfig.size / 100)}px`, 
                          height: `${qrCodeConfig.logoSize * (qrCodeConfig.size / 100)}px`,
                          borderRadius: `${qrCodeConfig.logoRoundedCorners}%`
                        }}
                      >
                        <img 
                          src={qrCodeConfig.logoUrl} 
                          alt="Logo" 
                          className="w-full h-full object-contain"
                        />
                      </div>
                    </div>
                  )}
                </div>
              </motion.div>
            ) : isLoading ? (
              <motion.div
                key="loading"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className={`flex items-center justify-center rounded-xl ${isDark ? 'bg-gray-700' : 'bg-gray-100'} mb-6`}
                style={{ width: `${qrCodeConfig.size}px`, height: `${qrCodeConfig.size}px` }}
              >
                <div className="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-blue-500"></div>
              </motion.div>
            ) : (
              <motion.div
                key="empty"
                initial={{ opacity: 0 }}
                animate={{ opacity: 1 }}
                exit={{ opacity: 0 }}
                className={`flex flex-col items-center justify-center rounded-xl ${isDark ? 'bg-gray-700' : 'bg-gray-100'} mb-6`}
                style={{ width: `${qrCodeConfig.size}px`, height: `${qrCodeConfig.size}px` }}
              >
                <i className="fa-solid fa-qrcode text-5xl mb-3 text-gray-400"></i>
                <p className={`text-sm ${isDark ? 'text-gray-400' : 'text-gray-500'}`}>
                  输入内容后将显示二维码
                </p>
              </motion.div>
            )}
          </AnimatePresence>
          
          {/* 操作按钮 */}
          <div className="flex flex-wrap gap-3 justify-center w-full">
            <motion.button
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={handleCopyToClipboard}
              disabled={!qrCodeValue || isLoading}
              className={`flex items-center gap-2 px-5 py-2.5 rounded-lg transition-colors ${
                qrCodeValue && !isLoading 
                  ? 'bg-blue-500 hover:bg-blue-600 text-white' 
                  : 'bg-gray-300 text-gray-500 cursor-not-allowed'
              }`}
            >
              <i className="fa-regular fa-copy"></i>
              复制到剪贴板
            </motion.button>
            
            <motion.button
              whileHover={{ scale: 1.05 }}
              whileTap={{ scale: 0.95 }}
              onClick={handleDownloadQRCode}
              disabled={!qrCodeValue || isLoading}
              className={`flex items-center gap-2 px-5 py-2.5 rounded-lg transition-colors ${
                qrCodeValue && !isLoading 
                  ? isDark 
                    ? 'bg-gray-700 hover:bg-gray-600 text-white' 
                    : 'bg-gray-100 hover:bg-gray-200 text-gray-800'
                  : 'bg-gray-300 text-gray-500 cursor-not-allowed'
              }`}
            >
              <i className="fa-solid fa-download"></i>
              下载图片
            </motion.button>
          </div>
          
          {/* 样式配置面板 */}
          <QRCodeConfigPanel 
            config={qrCodeConfig} 
            onConfigChange={setQrCodeConfig} 
          />
        </div>
      </div>
      
      {/* 功能说明 */}
      <div className={`mt-6 p-4 rounded-lg ${isDark ? 'bg-gray-800' : 'bg-white'} shadow-sm transition-colors duration-300`}>
        <h3 className="text-lg font-medium mb-3 text-center">功能特点</h3>
        <ul className="grid grid-cols-1 md:grid-cols-2 gap-3">
          <li className="flex items-start gap-2">
            <i className="fa-check-circle text-green-500 mt-0.5"></i>
            <span className="text-sm">即时生成，无需额外点击按钮</span>
          </li>
          <li className="flex items-start gap-2">
            <i className="fa-check-circle text-green-500 mt-0.5"></i>
            <span className="text-sm">支持网址和纯文本内容</span>
          </li>
          <li className="flex items-start gap-2">
            <i className="fa-check-circle text-green-500 mt-0.5"></i>
            <span className="text-sm">自定义样式，多种配置选项</span>
          </li>
          <li className="flex items-start gap-2">
            <i className="fa-check-circle text-green-500 mt-0.5"></i>
            <span className="text-sm">可添加中间logo或上传本地图片，个性化定制</span>
          </li>
          <li className="flex items-start gap-2">
            <i className="fa-check-circle text-green-500 mt-0.5"></i>
            <span className="text-sm">无需注册登录，完全匿名使用</span>
          </li>
          <li className="flex items-start gap-2">
            <i className="fa-check-circle text-green-500 mt-0.5"></i>
            <span className="text-sm">响应式设计，适配各种设备</span>
          </li>
        </ul>
      </div>
    </>
  );
}